package com.example.j2025_11_14.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import com.example.j2025_11_14.model.Session;
import com.example.j2025_11_14.model.Size;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private Size size;
    @Autowired
    private Session Session;

    private final static long TIME = 60* 1000L;
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) {
        LineCaptcha lineCaptcha =  CaptchaUtil.createLineCaptcha(size.getWidth(), size.getLength());;
        try {

            lineCaptcha.write(response.getOutputStream());
            //向session存数据
            session.setAttribute(Session.getKey(), lineCaptcha.getCode());
            //向session存时间
            session.setAttribute(Session.getDate(), new Date());

            //设置文本格式
            response.setContentType("image/jpeg");
            //禁⽌使⽤缓存
            response.setHeader("Pragma", "No-cache");

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            System.out.println("⽣成的验证码:" + lineCaptcha.getCode());
            System.out.println((String) session.getAttribute(Session.getKey()));
            System.out.println(Session.getDate());
            System.out.println(Session.getKey());
            System.out.println((Date)session.getAttribute(Session.getDate()));
        }
    }
    @RequestMapping("/check")
    public Boolean check(HttpSession session,String captcha){
        if (!StringUtils.hasLength(captcha)){
            return false;
        }
        String sessionKey = (String) session.getAttribute(Session.getKey());
        Date date = (Date) session.getAttribute(Session.getDate());
        if (!(captcha).equalsIgnoreCase(sessionKey) || System.currentTimeMillis() - date.getTime() > TIME){
            return false;
        }
        //忽略大小写
        return captcha.equalsIgnoreCase(sessionKey);
    }
}
